package cn.hss.jdbc;

import cn.hss.jdbc.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.Scanner;

/**模拟登录功能，演示SQL注入
 * @author 作者：HeShaoShuai
 * @Email 邮箱：2569819541@qq.com
 * @Date 日期：2023/5/6 8:05
 * @Package 包名：cn.hss.jdbc
 * @Project 项目名：JavaSE
 * @Version 1.0
 */
public class JDBCDemo1 {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		System.out.println("请输入用户名：");
		String userName = sca.nextLine();
		System.out.println("请输入密码：");
		String pwd = sca.nextLine();
		//把用户名和密码传递到数据库进行校验
		//boolean flag = login(userName, pwd);
		boolean flag = tologin(userName,pwd);
		if (flag) {
			System.out.println("欢迎" + userName + "登录成功");
		} else {
			System.out.println("用户名或密码错误！！");
		}
	}
	//使用预编译对象解决SQL注入问题
	private static boolean tologin(String name,String password) {
		ResultSet rs=null;
		PreparedStatement ps =null;
		Connection conn =null;
		//参数进行校验
		if(name==null || password==null){
			return false;
		}

		try {
			//注册驱动和获取连接
			conn = JDBCUtil.getConn();
			//定义sql语句
			String sql="select * from user " +
					"where username=? and password=?";
			//创建执行SQL的传输器对象
			ps = conn.prepareStatement(sql);
			//设置问号占位符
			ps.setObject(1, name);
			ps.setObject(2, password);
			//执行SQL
			rs = ps.executeQuery();
			return rs.next();
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			//释放资源
			JDBCUtil.closeIO(rs);
			JDBCUtil.closeIO(ps);
			JDBCUtil.closeIO(conn);
		}
		return false;
	}
	public static boolean login(String name,String password){
		ResultSet rs=null;
		Statement statement =null;
		Connection conn =null;
		//参数进行校验
		if(name==null || password==null){
			return false;
		}

		try {
			//注册驱动和获取连接
			conn = JDBCUtil.getConn();
			//定义sql语句
			String sql="select * from user " +
					"where username='"+name+"' and password='"+password+"'";
			//创建执行SQL的传输器东西
			statement = conn.createStatement();
			//执行SQL
			rs = statement.executeQuery(sql);
//            boolean next = rs.next();
//            return next;
			return rs.next();
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			//释放资源
			JDBCUtil.closeIO(rs);
			JDBCUtil.closeIO(statement);
			JDBCUtil.closeIO(conn);
		}
		return false;
	}

}